package jmine.tec.web.servlet.taglib;

import java.io.IOException;
import java.security.Principal;

import javax.security.auth.Subject;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;

import bancosys.tec.security.impl.web.WebSecurityManager;

/**
 * Tag de componente JSF que mostra usuario corrente.
 * 
 * @author Marcio Ribeiro (mmr)
 * @created Aug 29, 2008
 * @see UIShowCurrentUser
 */
public class ShowCurrentUserTag extends TagSupport {

    private String style;

    /**
     * @return o valor do campo styleClass
     */
    public String getStyleClass() {
        return this.style;
    }

    /**
     * @param styleClass o valor para o campo styleClass
     */
    public void setStyleClass(String styleClass) {
        this.style = styleClass;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public int doEndTag() throws JspException {
        Subject subject = (Subject) this.pageContext.getSession().getAttribute(WebSecurityManager.SESSION_KEY);
        if (subject != null) {
            Principal principal = subject.getPrincipals().iterator().next();
            String userName = principal.getName();
            if (userName != null) {
                StringBuffer sb = new StringBuffer();
                sb.append("<span ");
                if (this.style != null && !"".equals(this.style)) {
                    sb.append("class=\"" + this.style + "\" ");
                }
                sb.append(">");
                sb.append(userName);
                sb.append("</span>");

                try {
                    this.pageContext.getOut().write(sb.toString());
                } catch (IOException e) {
                    throw new JspException(e);
                }
            }
        }

        return super.doEndTag();
    }

}